package com.chenjinyan.back.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chenjinyan.back.dao.PicRepository;
import com.chenjinyan.back.entity.PicEntity;
import com.chenjinyan.back.service.PicService;
import com.chenjinyan.back.utils.ResultUtil;
import com.chenjinyan.back.utils.StringUtils;
import com.chenjinyan.back.vo.PicVo;
import com.chenjinyan.back.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PicServiceImpl implements PicService {

    @Autowired
    PicRepository picRepository;

    @PersistenceContext
    private EntityManager em;

    @Override
    public PicEntity insertPic(PicEntity picEntity) throws ParseException {
        PicEntity picEntityNew = picRepository.saveAndFlush(picEntity);
        return picEntityNew;
    }

    @Override
    public Result getPic(PicVo picVo) throws ParseException {
        Result result = ResultUtil.success();
        Long id = picVo.getId();
        String backPicUrl = picVo.getBackPicUrl();
        String description = picVo.getDescription();
        String pageNo = picVo.getPageNo();
        String pageSize = picVo.getPageSize();

        Map<String, String> map = new HashMap<>(16);

        if (null == pageNo || "".equals(pageNo)) {
            pageNo = "1";
        }
        if (null == pageSize || "".equals(pageSize)) {
            pageSize = "20";
        }
        StringBuilder sql = builderSql();
        StringBuilder sqlCount = builderSqlCount();

        if (null != id) {
            //用户id
            sql.append("AND ID=:id ");
            sqlCount.append("AND ID=:id ");
        }
        if (null != backPicUrl) {
            //失物种类
            sql.append("AND GOODS_PIC_URL=:backPicUrl ");
            sqlCount.append("AND GOODS_PIC_URL=:backPicUrl ");
        }
        if (null != description) {
            //开始时间
            sql.append("AND DESCRIPTION=:description ");
            sqlCount.append("AND DESCRIPTION=:description ");
        }
        Query q = em.createNativeQuery(sql.toString(), PicEntity.class);
        Query countQ = em.createNativeQuery(sqlCount.toString(), PicEntity.class);

        if (null != id) {
            q.setParameter("id", id);
            countQ.setParameter("id", id);
        }

        if (!StringUtils.isEmpty(backPicUrl) && !StringUtils.isEmpty(backPicUrl)) {
            q.setParameter("backPicUrl", backPicUrl);
            countQ.setParameter("backPicUrl", backPicUrl);
        }

        if (!StringUtils.isEmpty(description) && !StringUtils.isEmpty(description)) {
            q.setParameter("description", description);
            countQ.setParameter("description", description);
        }
        q.setFirstResult((Integer.parseInt(pageNo) - 1) * Integer.parseInt(pageSize));
        q.setMaxResults(Integer.parseInt(pageSize));
        List<PicEntity> list = q.getResultList();

        Integer recordCount = countQ.getResultList().size();
        //Integer recordCount = q.getResultList().size();
        Long pageCount = getPageCount(Integer.parseInt(pageSize), recordCount.longValue());

        map.put("currentPage", pageNo);
        map.put("pageSize", pageSize);
        map.put("recordCount", String.valueOf(recordCount));

        map.put("currentPage", pageNo);
        map.put("pageSize", pageSize);
        map.put("recordCount", String.valueOf(recordCount));
        if (pageCount == 0) {
            pageCount++;
        }
        map.put("pageCount", String.valueOf(pageCount));
        map.put("data", JSONObject.toJSONString(list, SerializerFeature.WriteMapNullValue));
        result.setData(map);
        return result;
    }

    @Override
    public Result delPic(List<String> ids) throws ParseException {
        Result result = ResultUtil.success();
        StringBuilder sql = builderDelSql();
        Query q = em.createNativeQuery(sql.toString());
        q.setParameter("ids", ids);
        int i = q.executeUpdate();
        if(i>0){
            result.setMsg("删除成功");
        }else{
            result.setMsg("删除失败，请检查传入id");
        }
        return result;
    }

    private StringBuilder builderDelSql() {
        StringBuilder sql = new StringBuilder(500);
        sql.append("DELETE ")
                .append("FROM lost_and_find_back_pic ")
                .append("WHERE ID IN :ids ");
        return sql;
    }

    private StringBuilder builderSql() {
        StringBuilder sql = new StringBuilder(500);
        sql.append("SELECT ")
                .append("ID,BACK_PIC_URL,DESCRIPTION ")
                .append("FROM lost_and_find_back_pic ")
                .append("WHERE 1=1 ");
        return sql;
    }

    private StringBuilder builderSqlCount() {
        StringBuilder sql = new StringBuilder(500);
        sql.append("SELECT ")
                .append("ID,BACK_PIC_URL,DESCRIPTION ")
                .append("FROM lost_and_find_back_pic ")
                .append("WHERE 1=1 ");
        return sql;
    }

    private Long getPageCount(Integer pageSize, Long recordCount) {
        return recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1;
    }

}
